﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using DocumentMaking.FluentNext.Dialogs;
using DocumentMaking.FluentNext.Models;
using FluentAvalonia.UI.Controls;

namespace DocumentMaking.FluentNext.Pages;

public partial class PythonPage : UserControl
{
    private string? PyPath { get; set; }
    private string? Error { get; set; }

    public PythonPage()
    {
        InitializeComponent();
        var pyPath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location)!, "PythonScripts", "info.json");
        if (!File.Exists(pyPath))
        {
#if DEBUG
            var directory = AppContext.BaseDirectory.Split(Path.DirectorySeparatorChar);
            var slice = new ArraySegment<string>(directory, 0, directory.Length - 4);
            pyPath = Path.Combine(Path.GetDirectoryName(Path.Combine(slice.ToArray()))!, "DocPython", "PythonScripts",
                "info.json");
            if (!File.Exists(pyPath))
            {
                Error = $"没有该文件: {pyPath}";
                return;
            }
#elif TRACE
            Error = $"没有该文件: {pyPath}";
            return;
#endif
        }

        PyPath = pyPath.Replace("info.json", "");
        var info = JsonSerializer.Deserialize<PythonFileInfoModel[]>(File.ReadAllText(pyPath));
        if (info == null || info.Length == 0)
        {
            info = PythonFileInfoModel.GetDefault();
            File.WriteAllText(pyPath, JsonSerializer.Serialize(info));
        }

        ItemsControl.ItemsSource = info;
    }

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        if(string.IsNullOrEmpty(Error))return;
        ShowInfo(this.GetDialog(Error));
        Expander.IsVisible = false;
    }

    private async void ShowInfo(TaskDialog dialog)
    {
        dialog.XamlRoot = (Visual)VisualRoot!;
        await dialog.ShowAsync();
    }

    private void SelectionClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not PythonFileInfoModel model) return;
        Process.Start(new ProcessStartInfo() { FileName = PyPath + model.FileName + ".py", UseShellExecute = true });
        var td = new TaskDialog
        {
            Title = "文档生成工具",
            Content = $"正在打开该文件: {model.FileName + ".py"}",
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton
            }
        };
        ShowInfo(td);
    }

    private void InitClick(object? sender, RoutedEventArgs e)
    {
        var cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
        cmd.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
        cmd.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
        cmd.StartInfo.RedirectStandardError = true; //重定向标准错误输出
        cmd.Start();
        cmd.StandardInput.WriteLine($"cd {PyPath}");
        cmd.StandardInput.WriteLine("pip install -r requirements.txt");
        cmd.StandardInput.Close();
        Console.WriteLine(cmd.StandardOutput.ReadToEnd());
        cmd.Close();
        cmd.Dispose();
    }
}